import { CheckAns } from "./CheckAns";

namespace Offer0003FindRepeatNumber {
    // 直接用数组方法算
    function findRepeatNumber(nums: number[]): number {
        if (!nums || nums.length == 0) return 0;
        for (let i = 0; i < nums.length; i++) {
            const num = nums[i];
            if (nums.lastIndexOf(num) != i) {
                return num;
            }
        }
        return 0;
    };

    // 优化一下效率，减少遍历次数
    function findRepeatNumber1(nums: number[]): number {
        if (!nums || nums.length == 0) return 0;
        // 使用set数据结构辅助计算
        let set: Set<number> = new Set();
        for (const num of nums) {
            if (set.has(num))
                return num;
            else
                set.add(num);
        }
        return 0;
    }

    // test
    const testData: { nums: number[], ans: number }[] = [
        { nums: [2, 3, 1, 0, 2, 5, 3], ans: 2 }
    ];
    for (const data of testData) {
        const ans = findRepeatNumber1(data.nums);
        CheckAns(data, ans);
    }
}